import { AIProvider, AIProviderConfig, ImageGenerationRequest, ImageGenerationResponse } from './AIProvider';
const OpenAI = require('openai');

export interface OpenAIConfig extends AIProviderConfig {
  organization?: string;
  model?: string;
  defaultSize?: string;
  defaultQuality?: string;
  defaultStyle?: string;
}

export class OpenAIProvider extends AIProvider {
  private client: any;
  private openaiConfig: OpenAIConfig;

  constructor(config: OpenAIConfig) {
    super(config);
    this.openaiConfig = config;
    this.validateConfig();
    this.initializeClient();
  }

  protected validateConfig(): void {
    if (!this.config.apiKey) {
      throw new Error('OpenAI API Key is required');
    }
  }

  private initializeClient(): void {
    try {
      this.client = new OpenAI({
        apiKey: this.config.apiKey,
        organization: this.openaiConfig.organization,
        baseURL: this.config.baseURL,
        timeout: this.config.timeout || 60000,
        maxRetries: this.config.maxRetries || 3
      });
    } catch (error) {
      console.error('Failed to initialize OpenAI client:', error);
      throw error;
    }
  }

  isAvailable(): boolean {
    return !!this.client && !!this.config.apiKey;
  }

  async generateImage(request: ImageGenerationRequest): Promise<ImageGenerationResponse> {
    if (!this.isAvailable()) {
      throw new Error('OpenAI provider is not available');
    }

    try {
      const response = await this.client.images.generate({
        model: this.openaiConfig.model || 'dall-e-3',
        prompt: request.prompt,
        size: request.size || this.openaiConfig.defaultSize || '1024x1024',
        quality: request.quality || this.openaiConfig.defaultQuality || 'standard',
        style: request.style || this.openaiConfig.defaultStyle || 'vivid',
        response_format: 'url',
        n: request.n || 1
      });

      if (!response.data || response.data.length === 0) {
        throw new Error('OpenAI did not return any generated images');
      }

      const imageUrl = response.data[0].url;
      if (!imageUrl) {
        throw new Error('Generated image URL is empty');
      }

      return {
        imageUrl,
        requestId: response.id,
        metadata: {
          model: this.openaiConfig.model || 'dall-e-3',
          size: request.size || this.openaiConfig.defaultSize || '1024x1024',
          quality: request.quality || this.openaiConfig.defaultQuality || 'standard',
          style: request.style || this.openaiConfig.defaultStyle || 'vivid'
        }
      };
    } catch (error) {
      console.error('OpenAI image generation failed:', error);
      throw new Error(`OpenAI image generation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  getProviderName(): string {
    return 'OpenAI';
  }
}